package com.rpc.protocol.http;

import org.apache.commons.io.IOUtils;
import com.rpc.framework.Invocation;
import com.rpc.framework.URL;

import java.io.ObjectOutputStream;
import java.net.HttpURLConnection;

/**
 * @Author:cxy
 * @Date:2021/1/22 20:45
 */
public class HttpClient {

    /**
     * 发送接收数据
     * @param url 连接的url
     * @param invocation 方法对象参数
     * @return 响应
     */
    public String send(URL url, Invocation invocation){

        //创建一个HttpClient
       try {
           HttpURLConnection httpURLConnection = (HttpURLConnection) new java.net.URL("http", url.getHostname(), url.getPort(), "/").openConnection();
           httpURLConnection.setRequestMethod("POST");
           httpURLConnection.setDoOutput(true);
            //发送数据
           ObjectOutputStream oos = new ObjectOutputStream(httpURLConnection.getOutputStream());
           oos.writeObject(invocation);
           oos.flush();
           oos.close();
            //接收响应数据
           return IOUtils.toString(httpURLConnection.getInputStream()) ;

       }catch (Exception e){
            e.printStackTrace();
       }
        return null;

    }

}
